const fs = require('fs');
const path = require('path');
const turf = require('@turf/turf');

// 输入文件路径 - 使用之前处理过的文件
const inputFile = path.join(__dirname, 'nanjingvillage_processed.json');

// 输出文件路径
const outputFiles = {
  town: path.join(__dirname, 'nanjing_town_aggregated.json'),
  county: path.join(__dirname, 'nanjing_county_aggregated.json'),
  city: path.join(__dirname, 'nanjing_city_aggregated.json')
};

console.log('开始聚合GeoJSON数据...');

// 读取文件
fs.readFile(inputFile, 'utf8', (err, data) => {
  if (err) {
    console.error('读取文件失败:', err);
    return;
  }

  try {
    // 解析JSON数据
    const geojsonData = JSON.parse(data);

    // 检查数据类型是否为数组
    if (!Array.isArray(geojsonData)) {
      console.error('数据不是数组格式');
      return;
    }

    console.log(`找到 ${geojsonData.length} 个Feature对象`);

    // 1. 聚合到乡镇(town)层级
    console.log('开始聚合到乡镇层级...');
    const townFeatures = aggregateByLevel(geojsonData, 'town', feature => {
      // 乡镇代码是villageCode的前9位
      const villageCode = feature.properties.villageCode.replace(/\s/g, ''); // 去除空格
      return {
        id: villageCode.substring(0, 9),
        properties: {
          province: feature.properties.province,
          city: feature.properties.city,
          county: feature.properties.county,
          town: feature.properties.town,
          townCode: villageCode.substring(0, 9),
          countyCode: villageCode.substring(0, 6),
          villages: [feature.properties.village],
          villageCount: 1
        }
      };
    });

    // 2. 聚合到区县(county)层级
    console.log('开始聚合到区县层级...');
    const countyFeatures = aggregateByLevel(geojsonData, 'county', feature => {
      // 区县代码是villageCode的前6位
      const villageCode = feature.properties.villageCode.replace(/\s/g, ''); // 去除空格
      return {
        id: villageCode.substring(0, 6),
        properties: {
          province: feature.properties.province,
          city: feature.properties.city,
          county: feature.properties.county,
          countyCode: villageCode.substring(0, 6),
          towns: [feature.properties.town],
          townCount: 1,
          villages: [feature.properties.village],
          villageCount: 1
        }
      };
    });

    // 3. 聚合到城市(city)层级
    console.log('开始聚合到城市层级...');
    const cityFeatures = aggregateByLevel(geojsonData, 'city', feature => {
      // 城市ID使用adcode（通常城市的adcode是6位，与区县相同，但这里我们按city名称聚合）
      return {
        id: feature.properties.city,
        properties: {
          province: feature.properties.province,
          city: feature.properties.city,
          cityCode: feature.properties.adcode,
          counties: [feature.properties.county],
          countyCount: 1,
          towns: [feature.properties.town],
          townCount: 1,
          villages: [feature.properties.village],
          villageCount: 1
        }
      };
    });

    // 保存聚合后的文件
    saveAggregatedFile(outputFiles.town, townFeatures);
    saveAggregatedFile(outputFiles.county, countyFeatures);
    saveAggregatedFile(outputFiles.city, cityFeatures);

  } catch (error) {
    console.error('处理错误:', error);
  }
});

/**
 * 按指定层级聚合GeoJSON数据
 * @param {Array} features - 原始Feature数组
 * @param {string} level - 聚合层级（town/county/city）
 * @param {Function} getGroupInfo - 获取分组信息的函数
 * @returns {Array} 聚合后的Feature数组
 */
function aggregateByLevel(features, level, getGroupInfo) {
  // 用于存储聚合后的Feature
  const aggregated = {};

  // 遍历所有Feature进行聚合
  features.forEach(feature => {
    const groupInfo = getGroupInfo(feature);
    const id = groupInfo.id;
    
    // 如果是新的分组，创建新的Feature
    if (!aggregated[id]) {
      aggregated[id] = {
        type: 'Feature',
        geometry: feature.geometry,
        properties: groupInfo.properties
      };
    } else {
      // 如果是已存在的分组，使用turf合并几何图形和属性
      aggregated[id].geometry = mergeGeometriesWithTurf(aggregated[id].geometry, feature.geometry);
      
      // 更新属性统计信息
      if (groupInfo.properties.villages) {
        aggregated[id].properties.villages = [...new Set([...aggregated[id].properties.villages, ...groupInfo.properties.villages])];
        aggregated[id].properties.villageCount = aggregated[id].properties.villages.length;
      }
      
      if (groupInfo.properties.towns) {
        aggregated[id].properties.towns = [...new Set([...aggregated[id].properties.towns, ...groupInfo.properties.towns])];
        aggregated[id].properties.townCount = aggregated[id].properties.towns.length;
      }
      
      if (groupInfo.properties.counties) {
        aggregated[id].properties.counties = [...new Set([...aggregated[id].properties.counties, ...groupInfo.properties.counties])];
        aggregated[id].properties.countyCount = aggregated[id].properties.counties.length;
      }
    }
  });

  // 转换为数组返回
  return Object.values(aggregated);
}

/**
 * 使用turf.js合并两个几何图形
 * @param {Object} geom1 - 第一个几何图形
 * @param {Object} geom2 - 第二个几何图形
 * @returns {Object} 合并后的几何图形（确保为Polygon类型）
 */
function mergeGeometriesWithTurf(geom1, geom2) {
  try {
    // 确保输入的几何体是有效的
    if (!geom1 || !geom2) {
      return geom1 || geom2;
    }
    
    // 创建turf的Feature对象
    const feature1 = turf.feature(geom1);
    const feature2 = turf.feature(geom2);
    
    // 使用turf.union合并几何图形
    const union = turf.union(feature1, feature2);
    
    if (union && union.geometry) {
      // 如果结果是MultiPolygon，尝试转换为Polygon
      if (union.geometry.type === 'MultiPolygon' && union.geometry.coordinates.length === 1) {
        return {
          type: 'Polygon',
          coordinates: union.geometry.coordinates[0]
        };
      }
      return union.geometry;
    }
    
    // 如果合并失败，返回原始的geom1
    return geom1;
  } catch (error) {
    console.warn('几何图形合并失败:', error.message);
    // 合并失败时返回原始的geom1
    return geom1;
  }
}

/**
 * 保存聚合后的GeoJSON文件
 * @param {string} filePath - 文件路径
 * @param {Array} features - Feature数组
 */
function saveAggregatedFile(filePath, features) {
  const geojson = {
    type: 'FeatureCollection',
    features: features
  };

  fs.writeFile(filePath, JSON.stringify(geojson, null, 2), 'utf8', (err) => {
    if (err) {
      console.error(`保存文件 ${filePath} 失败:`, err);
      return;
    }
    console.log(`聚合文件已成功保存到: ${filePath}`);
    console.log(`包含 ${features.length} 个${filePath.includes('town') ? '乡镇' : filePath.includes('county') ? '区县' : '城市'} Feature对象`);
  });
}